<template>
  <div>
    <a-form :model="form" :rules="rules">
      <template v-for="(field, index) in formField" :key="field.id">
        <a-form-item
          :label="geta(field.props.label, field.componentName, field.props.unit)"
          :name="field.id"
          :label-col="{ span: 24 }"
          :wrapper-col="{ span: 24 }"
          :rules="[{ required: field.props.required, message: '必填字段' }]"
        >
          <!-- TitleField =>标题 -->
          <template
            v-if="
              field.type === 'input' ||
              field.componentName === 'TitleField' ||
              field.componentName === 'TextField' ||
              field.componentName === 'FontSizeField' ||
              field.componentName === 'IssuingUnitField' ||
              field.componentName === 'MasterSendField' ||
              field.componentName === 'CopySendField' ||
              field.componentName === 'TitleTermField'
            "
          >
            <a-input
              v-model:value="field.props.content"
              :placeholder="field.props.placeholder"
              :maxlength="field.componentName === 'TitleField' ? 100 : 50"
              class="single-input"
              :class="field.componentName === 'TitleField' ? 'single-inputs' : null"
              @change="change(field.componentName, index)"
            />
            <span class="num"
              >{{ field.props.content.length }}/{{
                field.componentName === 'TitleField' ? 100 : 50
              }}</span
            >
          </template>
          <!-- 多个部门 -->
          <template v-if="field.componentName === 'bumen'">
            <a-radio-group
              v-model:value="field.props.content"
              @change="radioChange(field.props.content)"
            >
              <a-radio
                v-for="(item, i) in field.props.option"
                :key="i"
                :value="item.key"
                class="tag-item"
                >{{ item.value }}</a-radio
              >
            </a-radio-group>
          </template>
          <!-- 数字输入框 -->
          <template v-if="field.componentName === 'NumberField'">
            <a-input-number
              v-model:value="field.props.content"
              :placeholder="field.props.placeholder"
              :maxlength="50"
              class="single-input"
              @change="change(field.componentName, index)"
            />
          </template>
          <!-- 富文本 -->
          <template v-else-if="field.componentName === 'TextRichField'">
            <BasicEditor
              :catch-data="catchData"
              :catchpure-data="catchPureData"
              :content="wangEditorData"
              :style="'min'"
            ></BasicEditor>
          </template>
          <!-- 多行文本 -->
          <template
            v-else-if="field.type === 'textarea' || field.componentName === 'TextareaField'"
          >
            <a-textarea
              v-model:value="field.props.content"
              :placeholder="field.props.placeholder"
              :maxlength="1000"
              class="texts"
              @change="change(field.componentName, index)"
            />
            <span class="texts-num">{{ field.props.content.length }}/1000</span>
          </template>
          <!-- select 单选 -->
          <template
            v-else-if="
              field.type === 'select' ||
              field.componentName === 'DDSelectField' ||
              field.componentName === 'UrgencyLevelSelect' ||
              field.componentName === 'SecretLevelSelect'
            "
          >
            <a-select
              v-model:value="field.props.contents"
              :placeholder="field.props.placeholder"
              :field-names="{ label: 'key', value: 'value' }"
              @change="change(field.componentName, index, $event)"
            >
              <a-select-option
                v-for="option in getOptions(field.props.options)"
                :key="option.value"
                :placeholder="field.props.placeholder"
              >
                {{ option.value }}
              </a-select-option>
            </a-select>
          </template>
          <!-- DDMultiSelectField 多选 -->
          <template v-else-if="field.componentName === 'DDMultiSelectField'">
            <a-select
              v-model:value="field.props.contents"
              mode="tags"
              :placeholder="field.props.placeholder"
              @change="change(field.componentName, index, $event)"
            >
              <a-select-option
                v-for="option in getOptions(field.props.options)"
                :key="option.value"
                :value="option.value"
                :placeholder="field.props.placeholder"
              >
                {{ option.value }}
              </a-select-option>
            </a-select>
          </template>
          <!-- 日期 AM:PM -->
          <template
            v-else-if="
              field.type === 'date-picker' ||
              field.componentName === 'DDDateField' ||
              field.componentName === 'ReceivedOnDate' ||
              field.componentName === 'SendOnDate'
            "
          >
            <!-- 开发期间需要加一个 日期  上午下午的  然后就用不同的方法获取不同的类型， 测试阶段改成了两个框 所以留下很多无用方法 -->
            <a-date-picker
              v-if="getLast(field.props.format)"
              v-model:value="field.props.contents"
              :placeholder="field.props.placeholder"
              :show-time="{ formant: getLast(field.props.format) }"
              :format="hetHH(field.props.format)"
              @change="changeDate"
              @ok="ok(index)"
              @openChange="ok(index)"
            />
            <a-date-picker
              v-else
              v-model:value="field.props.contents"
              :placeholder="field.props.placeholder"
              :format="hetHH(field.props.format)"
              @change="changeDate"
              @openChange="ok(index)"
            />
          </template>
          <!-- 选人 -->
          <template v-else-if="field.componentName === 'InnerContactField'">
            <div
              class="people-box"
              @click.stop="
                openPeople(field.componentName, field.props.multiple, index, field.props.echoData)
              "
            >
              <span v-if="!field.props.echoData" class="tips">{{ field.props.placeholder }}</span>
              <div class="all-people">
                <template v-for="(item, index) in field.props.echoData" :key="item.id">
                  <div v-if="index < 10" class="people-item">
                    <div class="name">{{ item.userName }}</div>
                    <img
                      src="../../assets/img/oa_icon_close@2x.png"
                      alt=""
                      @click="deletePeople(field.props.echoData, item.userId)"
                    />
                  </div>
                </template>
                <div v-if="field.props.echoData?.length > 10">...</div>
              </div>
              <img
                src="../../assets/img/calendar_icon_month_right@2x.png"
                alt=""
                class="to-people"
              />
            </div>
            <!-- 表单 -->
            <MyPickProple
              v-if="visible"
              v-model:visible="visible"
              :max-count="maxCount"
              :appoint-state="appointState"
              :role-lists="roleList"
              :contacts-list="contactsList"
              :type="'people'"
              :echo-data="echoData"
              @onOK="updateMember"
            ></MyPickProple>
          </template>
          <template v-else-if="field.type === 'upload' || field.componentName === 'DDAttachment'">
            <a-upload
              v-model:file-list="field.fileList"
              list-type="picture"
              accept=".txt, .doc, .docx, .xls, .xlsx, .ppt, .pptx, .pdf, .jpg, .jpeg, .png, .mp4, .mp3,.wps, .ofd, .zip, .rar, .7z"
              :multiple="true"
              :remove="deleteFiless"
              :max-count="20"
              :custom-request="customRequest"
              @click="uploadClick(index)"
            >
              <a-button :disabled="field.fileList?.length >= 20" class="upload-box">
                <svg-icon
                  icon-class="icon_download_normals"
                  class-name="icon-select-date"
                ></svg-icon>
                点击上传
              </a-button>
            </a-upload>
            <div class="annex-box">
              <div v-for="item in field.annexList" :key="item.id" class="annex-item">
                <div class="left">
                  <img :src="getFengmian(item.fileType)" alt="" />
                  <div v-if="item.previewType === 'noPreview'" class="url-name" @click="look(item)">
                    {{ item.name }}
                    <!-- --{{ item.num }} -->
                  </div>
                  <div v-else class="ur-name" @click="lookUrl(item)">{{ item.name }}</div>
                </div>
                <div class="btn-list">
                  <svg-icon
                    icon-class="btn_icon_download"
                    class-name="icon-select-date"
                    @click="download(item.url)"
                  ></svg-icon>
                  <svg-icon
                    icon-class="btn_icon_delete"
                    class-name="icon-select-dates"
                    @click="deleteFile(item, index)"
                  ></svg-icon>
                </div>
              </div>
            </div>
          </template>
        </a-form-item>
      </template>
    </a-form>
  </div>
  <!-- 提交弹窗 -->
  <a-modal
    v-model:visible="passVisible"
    class="return-box"
    width="472px"
    :closable="false"
    :footer="null"
  >
    <div class="model-head">
      <div class="head-left">
        <div class="chexiao">{{ passTitle }}</div>
      </div>
      <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="passCancel" />
    </div>
    <div class="model-body">
      <div class="body-head">
        <div> 处理意见 </div>
      </div>
      <a-textarea
        v-model:value="passValue"
        class="input-box"
        placeholder="请输入内容"
        :maxlength="100"
        :auto-size="{ minRows: 2, maxRows: 4 }"
      >
      </a-textarea>
      <span class="nums"> {{ passValue.length }}/100</span>
    </div>
    <div class="btn-list">
      <a-button @click="passCancel">取消</a-button>
      <a-button type="primary" @click="passOk">确定</a-button>
    </div>
  </a-modal>
  <!-- 删除弹窗 -->
  <a-modal
    v-model:visible="deleteVisible"
    class="return-box"
    width="340px"
    :closable="false"
    :footer="null"
  >
    <div class="model-head">
      <div class="head-left">
        <img src="../../assets/img/xiangqing_icon_tixing@2x.png" alt="" />
        <div>提示</div>
      </div>
      <img src="../../assets/img/oa_icon_close@2x.png" alt="" @click="deleteCancel" />
    </div>
    <div class="model-body"> 确定要删除这个文件吗？ </div>
    <div class="btn-list">
      <a-button @click="deleteCancel">取消</a-button>
      <a-button type="primary" @click="deleteOk">确定</a-button>
    </div>
  </a-modal>
  <LoadingImage v-show="isLoadings"></LoadingImage>
</template>

<script setup>
import BasicEditor from '../../components/wangEditor/index.vue';
import LoadingImage from '@/components/loadingComponent/index.vue';
import {
  reactive,
  ref,
  defineProps,
  onMounted,
  nextTick,
  defineEmits,
  defineExpose,
  watch,
  provide
} from 'vue';
import {
  getAccessGet,
  getDeptTree,
  runtimeTask,
  updateDocumentHandler,
  getRelationSchoolRoleStruct,
  getFrequentContacts
} from '@/api/receiveDetails';
import { Form, Input, Select, DatePicker, Button, message } from 'ant-design-vue';
import ObsClient from 'esdk-obs-browserjs';
import { TjPickAndGroup } from 'tj-design-vue';
import moment from 'moment';
import dayjs from 'dayjs';
import MyPickProple from '@/components/pickProple/index.vue';
import store from '../../store';
import { useRoute, useRouter } from 'vue-router';
const route = useRoute();
const router = useRouter();
let isLoadings = ref(false);
function radioChange(val) {
  emit('changeRadio', val); // 是否页面有更改
}
let props = defineProps({
  formFields: {
    type: Array,
    required: true
  },
  lineData: {
    // 流程所有人
    type: Array,
    required: true
  },
  getInfo: {
    // 所有表单参数
  }
});
function geta(label, componentName, unit) {
  return label;
} //  处理url
function lookUrl(item) {
  console.log(222, item);
  if (
    item.fileType === 'rar' ||
    item.fileType === '7z' ||
    item.fileType === 'zip' ||
    item.fileType === 'RAR' ||
    item.fileType === 'ZIP' ||
    item.fileType === '7Z'
  ) {
    message.warning('文件类型不支持预览，请下载后查看');
    return;
  }
  let notice = {
    appData: {
      springAppName: 'resourcePool',
      url: `https://ow365.cn/?i=${iValue.value}&ssl=1&pct=1&furl=${item.url}`, //  带参数的完整链接
      title: item.name
    }
  };
  window.microappSDK.openDialogWindow(notice);
}
let formField = ref(); // 数据
watch(props, (newValue, oldValue) => {
  formField.value = newValue.formFields;
});
onMounted(() => {
  console.log(process.env, 89898);
  if (process.env.VUE_APP_WEB_URLS === 'dev' || process.env.VUE_APP_WEB_URLS === 'test') {
    bucket.value = 'tj-saas-test';
    iValue.value = 30237;
  }
  if (process.env.VUE_APP_WEB_URLS === 'preview') {
    bucket.value = 'saas-pre';
    iValue.value = 32109;
  }
  if (process.env.VUE_APP_WEB_URLS === 'pro') {
    bucket.value = 'resource-pool-obs';
    iValue.value = 29781;
  }
});
// 处理select数据
function getOptions(data) {
  return JSON.parse(data);
}
const appointState = ref(false); // 是否是指定人员状态
const contactsList = ref([]); // 常用联系人
const roleList = ref([]); // 角色数组
const visible = ref(false); // 选人组件弹框
const echoData = ref([]); // 回显数据
let maxCount = ref('不限');
// 打开选人
async function openPeople(val, multiple, ind, datas) {
  fileIndex.value = ind;

  echoData.value = datas;
  // 角色接口
  await getRelationSchoolRoleStruct({}).then(res => {
    if (res.code * 1 === 200) {
      let data = res.data;
      console.log('角色接口', data);
      roleList.value = data;
      store.commit('user/roleList', data); // 指定人员固定架构
    }
  });
  // 常用联系人
  provide('contactsListq', []);
  store.commit('user/contactsList', []);
  // 组织结构接口
  await getDeptTree({}).then(res => {
    if (res.code * 1 === 200) {
      let allPeoples = []; // 所有人
      let peopleLists = []; // 所有人
      res.data.forEach(item => {
        item.listPeople.forEach(it => {
          peopleLists.push({ ...it });
        });
      });
      allPeoples = peopleLists;
      let allPeople = allPeoples.reduce((acc, curr) => {
        let existingItem = acc.find(item => item.userId === curr.userId);
        if (existingItem) {
          existingItem.deptName += `，${curr.deptName}`;
        } else {
          acc.push({ ...curr });
        }
        return acc;
      }, []);
      allPeople.forEach(item => {
        item.username = item.userName;
      });
      // console.log(allPeople, '所有人');
      res.data.forEach(item => {
        item.categoryId = item.schoolBusinessId;
      });
      console.log(res.data, '组织结构数据');
      store.commit('user/departmentDatas', res.data);
      store.commit('user/allPeoples', allPeople);
      if (multiple * 1 === 0) {
        maxCount.value = '1';
      } else {
        maxCount.value = allPeople.length;
      }
      visible.value = true; // 打开选人弹窗
    }
  });
}
// 取消人
function deletePeople(data, val) {
  console.log(3534, data, val);
  data = data.filter(item => item.userId !== val);
  console.log(data);
}
function updateMember(val) {
  echoData.value = val;
  let list = [];
  val.forEach(i => {
    list.push(i.userName);
  });
  formField.value.forEach((item, index) => {
    if (fileIndex.value * 1 === index * 1) {
      item.props.echoData = echoData.value;
      item.props.content = list.join(',');
    } else {
      if (!item.props.echoData) {
        item.props.echoData = null;
      }
    }
  });
}
// 获取 时分秒
function getLast(val) {
  if (val.length === 16) {
    if (val.substr(-1) === 'M') {
      return 'AM(PM)';
    } else {
      return val.slice(val.lastIndexOf(' ') + 1);
    }
  } else {
    return false;
  }
}
function hetHH(h) {
  if (h.length === 16) {
    if (h.substr(-1) === 'M') {
      return 'YY-MM-DD A';
    } else {
      return 'YYYY-MM-DD HH:mm';
    }
  }
  if (h.length === 10) return 'YYYY-MM-DD';
}
let inputValue = ref('');
let selectValue = ref('');
let dataValue = ref('');
let fileIndex = ref(0);
function ok(ind) {
  fileIndex.value = ind;
}
// 时间chage
// 'ReceivedOnDate'=年月日时分秒； DDDateField=上午下午
function changeDate(value, dateString) {
  if (!value) {
    formField.value.forEach((item, index) => {
      if (
        item.componentName === 'DDDateField' ||
        item.componentName === 'ReceivedOnDate' ||
        item.componentName === 'SendOnDate'
      ) {
        if (!item.props.contents) {
          item.props.content = null;
        }
      }
    });

    return;
  }
  setTimeout(() => {
    let dataA = new Date(dateString);
    let time = new Date(dataA);
    let newTime;
    formField.value.forEach((item, index) => {
      if (fileIndex.value === index) {
        if (
          item.componentName === 'DDDateField' ||
          item.componentName === 'ReceivedOnDate' ||
          item.componentName === 'SendOnDate'
        ) {
          if (item.props.format.length === 10) {
            newTime =
              time.getFullYear() +
              '-' +
              getValue(time.getMonth() + 1) +
              '-' +
              getValue(time.getDate());
            item.props.contents = dayjs(newTime, 'YYYY-MM-DD');
            item.props.content = newTime;
          }
          if (item.props.format.length === 16) {
            if (item.props.format.substr(-1) === 'M') {
              if (dateString.indexOf('凌') !== -1) {
                item.props.contents = dayjs(
                  '20' + dateString.slice(0, -3) + ' 10:00',
                  'YYYY-MM-DD HH:mm'
                );
                item.props.content = '20' + dateString.slice(0, -3) + ' 上午';
              }
              // 上午下午
              if (
                dateString.indexOf('中') !== -1 ||
                dateString.indexOf('下') !== -1 ||
                dateString.indexOf('晚') !== -1
              ) {
                item.props.contents = dayjs(
                  '20' + dateString.slice(0, -3) + ' 16:00',
                  'YYYY-MM-DD HH:mm'
                );
                item.props.content = '20' + dateString.slice(0, -3) + ' 下午';
              }
            } else {
              // 年月日时分
              newTime =
                time.getFullYear() +
                '-' +
                getValue(time.getMonth() + 1) +
                '-' +
                getValue(time.getDate()) +
                ' ' +
                getValue(time.getHours()) +
                '-' +
                getValue(time.getMinutes());
              item.props.contents = dayjs(newTime, 'YYYY-MM-DD HH:mm');
              item.props.content = newTime;
            }
          }
        }
      }
    });
  });
}
function getValue(val) {
  return val * 1 < 10 ? '0' + val : val;
}
const emit = defineEmits(['returnBtns', 'changeRadio']);
// 所有详情change事件
function change(val, index, aValue) {
  if (val === 'DDAttachment') {
    formField.value.forEach(item => {
      let url = [];
      if (item.componentName === 'DDAttachment') {
        item.annexList.forEach(it => {
          url.push(it.url);
        });
        // 附件相关
        item.props.content = url.join(`\\`);
      }
    });
  }
  // 富文本相关
  if (val === 'TextRichField') {
    formField.value.forEach(item => {
      if (item.componentName === val) {
        item.props.content = html.value;
      }
    });
  }
  // select 单
  if (val === 'DDSelectField' || val === 'UrgencyLevelSelect' || val === 'SecretLevelSelect') {
    formField.value.forEach(item => {
      if (item.componentName === val) {
        let data = JSON.parse(item.props.options);
        data.forEach(it => {
          if (it.value === aValue) item.props.content = it.key;
        });
      }
    });
  }
  // select 多
  if (val === 'DDMultiSelectField') {
    formField.value.forEach(item => {
      if (item.componentName === val) {
        let data = JSON.parse(item.props.options);
        let list = [];
        data.forEach(it => {
          aValue.forEach(i => {
            if (it.value === i) list.push(it.value);
          });
        });
        item.props.content = list.join(',');
      }
    });
  }
  let list = [];
  formField.value.forEach(item => {
    list.push(!item.props.content);
  });
  if (list.indexOf(false) !== -1) {
    emit('returnBtns', true); // 是否页面有更改
  } else {
    emit('returnBtns', false);
  }
}
const form = reactive({});
const rules = reactive({});
function getId(data) {
  let idList = [];
  data.forEach(item => {
    idList.push(item.id);
  });
  return idList;
}
// 正文附件url
let fileUrl = ref(''); // 正文附件url
let fileType = ref(''); // 正文附件状态 true 富文本正文； false=>上传url
function getFileUrl(type, url) {
  fileType.value = type;
  // type true=>true 富文本正文； false=>上传url
  fileUrl.value = url;
}
let flowPathData = ref([]); // 流程Data
// 获得流程数据
function allData(val) {
  flowPathData.value = val.filter(item => item.nodeName !== '创建人');
}
const handleSubmit = () => {
  let oldPeople = props.lineData.filter(item => item.nodeName !== '创建人');
  let liuchengList = []; // 流程是否位空
  flowPathData.value.forEach(item => {
    liuchengList.push(item.oaNodeUserDtoS.length === 0);
  });
  let list = [];
  formField.value.forEach(item => {
    if (item.props.required * 1 === 1) {
      list.push(!item.props.content);
    }
  });

  let aaList = []; // 为了限制 有固定人的情况
  oldPeople.forEach(item => {
    if (item.oaNodeUserDtoS.length === 0) {
      aaList.push(true);
    }
  });
  if (aaList.length === 0) {
    flowPathData.value = oldPeople;
  }
  if (list.indexOf(true) !== -1) {
    message.warning('请完善必填项信息');
    return;
  }
  if (liuchengList.length === 0 && aaList.length !== 0) {
    message.warning('请完善人员信息');
    return;
  } else {
    if (liuchengList.length !== 0) {
      if (liuchengList.indexOf(true) !== -1) {
        message.warning('请完善人员信息');
        return;
      }
    }
  }
  passVisible.value = true;
};
// 通过弹窗 相关
let passTitle = ref('提交');
let passVisible = ref(false);
let passValue = ref(''); // 通过备注
function passCancel() {
  passVisible.value = false;
  passValue.value = '';
}
let processForm = ref();
function passOk() {
  let obj = {}; // 审批人员
  for (let i = 0; i < flowPathData.value.length; i++) {
    obj[flowPathData.value[i].nodeId] = getId(
      flowPathData.value[i].oaNodeUserDtoS.people
        ? flowPathData.value[i].oaNodeUserDtoS.people
        : flowPathData.value[i].oaNodeUserDtoS
    );
  }
  let formAry = [];
  formField.value = formField.value.filter(item => item.componentName !== 'bumen');
  formField.value.forEach(item => {
    // if (item.props.content || item.props.content.length > 0) {
    formAry.push({
      attr: item.props.unit ? JSON.stringify({ unit: item.props.unit }) : null,
      formId: item.formId,
      uuid: item.uuid,
      cmpId: item.cmpId,
      label: item.props.label,
      componentName: item.componentName,
      content: item.props.content,
      options: item.props.options,
      approvedUserId: item.flowApplyStr,
      copyUserId: item.flowCcStr
    });
    // }
  });
  let p = {
    textType: '1', // 1=>pc; 2=>h5
    formId: route.query.id,
    processKey: props.getInfo.processId,
    assigneeList: obj,
    processInstanceId: '',
    documentText: fileType.value ? fileUrl.value : '', // 正文富文本
    textUrl: !fileType.value ? fileUrl.value : '', // 正文url
    reason: passValue.value,
    contentList: formAry
  };
  runtimeTask(p).then(res => {
    if (res.code === 200) {
      message.success('提交成功');
      passVisible.value = false;
      sessionStorage.setItem('tabsActive', '公文收发');
      sessionStorage.setItem('startingActive', '1');
      updateList();
      router.push({
        path: '/index'
      });
    } else {
      message.error(res.msg);
    }
  });
  passValue.value = '';
}
function updateList() {
  updateDocumentHandler({
    processInstanceId: '',
    formId: route.query.id
  }).then(res => {
    console.log('新的接口', res);
  });
}
defineExpose({ handleSubmit, allData, getFileUrl });
let fileList = ref([]); // 附件数组
let annexList = ref([]); // 附件展示list
// 删除附件
function deleteFiless(file) {}
let num = ref([]); // 数量
let filNum = ref(5); // 上传数量
// 上传附件
function uploadClick(inx) {
  fileIndex.value = inx;
}
function customRequest(file) {
  let fileName = file.file.name;
  let name = fileName.substring(0, fileName.lastIndexOf('.'));
  if ((file.file.size * 1) / 1024 / 1024 > 300) {
    file.file['status'] = 'error';
    file.file['response'] = '文件超出上传限制!';
    message.error('文件超出上传限制!');
    annexList.value.pop();
    formField.value[fileIndex.value].fileList = formField.value[fileIndex.value].fileList.filter(
      item => {
        return (item.size * 1) / 1024 / 1024 <= 300;
      }
    );
    return false;
  } else if (name.length > 100) {
    file.file['status'] = 'error';
    file.file['response'] = '图像名超出字符限制，请修改后重新上传!';
    message.error('图像名超出字符限制，请修改后重新上传!');
    annexList.value.pop();
    formField.value[fileIndex.value].fileList = formField.value[fileIndex.value].fileList.filter(
      item => {
        return item.name.length <= 100;
      }
    );
    return false;
  } else {
    isLoadings.value = true;
    file.file['num'] = [];
    if (file.file.type === 'video/mp4' || file.file.type === 'audio/mpeg') {
      file.file['previewType'] = 'noPreview';
    } else {
      file.file['previewType'] = 'preview';
    }
    file.file.num = formField.value[fileIndex.value].annexList || [];
    file.file.num.push(file.file);
    console.log(file.file.num.length);
    if (file.file.num.length > 20) {
      message.warning('最多上传20个附件');
      file.reject();
    }
    file.file['progressValue'] = 0;
    file.file['status'] = 'done';
    file.file['fileType'] = file.file.name.slice(file.file.name.lastIndexOf('.') + 1);
    file.file['time'] = moment().format('YYYY-MM-DD');
    file.file['math'] = Math.random();
    file.file['load'] = false;
    file.file['nameUrl'] = file.file.math + '/' + file.file.name.replace(/\s+/g, '');
    file.file['urlTime'] = 'documentCirculation/' + file.file.time + '/' + file.file.nameUrl;
    uploadOBS(file.file);
  }
}
let obsId = ref('');
let obsKey = ref('');
let iValue = ref(30237); // 预览 i 的值
let bucket = ref('tj-saas-test'); // 桶名
function uploadOBS(file) {
  if (process.env.VUE_APP_WEB_URLS === 'test') {
    bucket.value = 'tj-saas-test';
    iValue.value = 30237;
  }
  if (process.env.VUE_APP_WEB_URLS === 'preview') {
    bucket.value = 'saas-pre';
    iValue.value = 32109;
  }
  if (process.env.VUE_APP_WEB_URLS === 'pro') {
    bucket.value = 'resource-pool-obs';
    iValue.value = 29781;
  }

  let fileDir = file.urlTime;
  let SourceFile = file;
  let id;
  let key;
  getAccessGet().then(res => {
    console.log(res);
    id = res.data.Accesskeyid;
    key = res.data.Policy;
  });
  id = 'TODD7COQ9OY55YNUYHEC';
  key = 'DmX1sTbrl0OGRnPKDTlXvup6DP2S9Txe4hKy6eRO';
  obsId.value = id;
  obsKey.value = key;
  let obsClient = new ObsClient({
    access_key_id: 'TODD7COQ9OY55YNUYHEC',
    secret_access_key: 'DmX1sTbrl0OGRnPKDTlXvup6DP2S9Txe4hKy6eRO',
    server: 'https://obs.cn-east-3.myhuaweicloud.com'
  });
  obsClient.putObject(
    {
      Bucket: bucket.value,
      Key: fileDir,
      SourceFile: SourceFile, // 文件encodeURIComponent
      ProgressCallback: function (transferredAmount, totalAmount, totalSeconds) {
        // transferredAmount, totalAmount, totalSeconds 已上传的字节数、总字节数、已使用的时间
        file.progressValue = ((transferredAmount / totalAmount) * 100).toFixed(2) * 1;
      }
    },
    function (err, result) {
      store.commit('user/isLoading', false);
      if (err) {
        message.error('上传失败');
      } else {
        let list = [];
        let progressValues = [];
        isLoadings.value = false;
        message.success('上传成功');
        formField.value[fileIndex.value].fileList.forEach(item => {
          console.log('类型', item.originFileObj.fileType);
          if (item.status !== 'error') {
            list.push({
              fileType: item.originFileObj.fileType,
              url:
                `https://${bucket.value}.obs.cn-east-3.myhuaweicloud.com/documentCirculation/` +
                item.originFileObj.time +
                '/' +
                getfileUrl(item),
              name: item.originFileObj.name,
              nameUrl: item.originFileObj.nameUrl,
              previewType: item.originFileObj.previewType,
              data: item,
              num: item.originFileObj.num.length
            });
            // 获取多个上传视频的进度 都是100 与原数组匹配 关闭loading
            if (item.originFileObj.progressValue * 1 === 100) {
              progressValues.push(item.originFileObj.progressValue);
            }
          }
          setTimeout(() => {
            console.log(list);
            formField.value[fileIndex.value].annexList = list;
            change('DDAttachment');
          });
          if (progressValues.length === formField.value[fileIndex.value].fileList.length) {
            isLoadings.value = false;
          }
        });
      }
    }
  );
}
function getfileUrl(file) {
  let types = file.originFileObj.name
    .replace(/\s+/g, '')
    .substring(file.originFileObj.name.replace(/\s+/g, '').lastIndexOf('.'));
  let three = file.originFileObj.name.substring(0, file.originFileObj.name.lastIndexOf('.'));
  return file.name.indexOf('%') !== -1
    ? file.originFileObj.math + '/' + encodeURIComponent(three) + types
    : file.originFileObj.nameUrl;
}
function getFengmian(type) {
  console.log('类型', type);
  if (type === 'pdf') {
    return require('@/assets/img/popup_icon_pdf@2x.png');
  }
  if (type === 'xls' || type === 'xlsx') {
    return require('@/assets/img/icon_excel_48px@2x.png');
  }
  if (type === 'doc' || type === 'docx') {
    return require('@/assets/img/popup_icon_word@2x.png');
  }
  if (type === 'txt') {
    return require('@/assets/img/popup_icon_test@2x.png');
  }
  if (type === 'ppt' || type === 'pptx') {
    return require('@/assets/img/popup_icon_ppt@2x.png');
  }
  if (type === 'jpg' || type === 'jpeg' || type === 'png') {
    return require('@/assets/img/icon_img_48px@2x.png');
  }
  if (type === 'mp4') {
    return require('@/assets/img/icon_shipin_48px@2x.png');
  }
  if (type === 'mp3') {
    return require('@/assets/img/icon_weizhi_48px@2x.png');
  }
  if (type === 'ofd' || type === 'wps') {
    return require('@/assets/img/icon_wenjian_48px@2x.png');
  }
  if (
    type === 'rar' ||
    type === '7z' ||
    type === 'zip' ||
    type === 'RAR' ||
    type === 'ZIP' ||
    type === '7Z'
  ) {
    return require('@/assets/img/icon_wenjian_48px@2x.png');
  } else {
    return require('@/assets/img/icon_weizhi_48px@2x.png');
  }
}
function look(val) {
  message.warning('文件类型不支持预览，请下载后查看');
}
//  处理url
function getUrl(item) {
  return `https://ow365.cn/?i=${iValue.value}&ssl=1&pct=1&furl=${item.url}`;
}
function download(url) {
  window.location.href = url;
}
let deleteVisible = ref(false);
// 删除文件
let deleteUrl = ref(''); // 删除文件地址
function deleteFile(item, inx) {
  fileIndex.value = inx;
  deleteVisible.value = true;
  deleteUrl.value = item.nameUrl;
}
// 删除取消按钮
function deleteCancel() {
  deleteVisible.value = false;
}
// 删除确认按钮
function deleteOk() {
  formField.value[fileIndex.value].fileList = formField.value[fileIndex.value].fileList.filter(
    item => item.originFileObj.nameUrl !== deleteUrl.value
  );
  formField.value[fileIndex.value].annexList = formField.value[fileIndex.value].annexList.filter(
    item => item.nameUrl !== deleteUrl.value
  );
  deleteOBS(deleteUrl.value);
  deleteVisible.value = false;
  message.success('删除成功');
  change('DDAttachment');
}
// / 删除华为云数据
function deleteOBS(dataKey) {
  if (process.env.VUE_APP_WEB_URLS === 'dev' || process.env.VUE_APP_WEB_URLS === 'test') {
    bucket.value = 'tj-saas-test';
    iValue.value = 30237;
  }
  if (process.env.VUE_APP_WEB_URLS === 'preview') {
    bucket.value = 'saas-pre';
    iValue.value = 32109;
  }
  if (process.env.VUE_APP_WEB_URLS === 'pro') {
    bucket.value = 'resource-pool-obs';
    iValue.value = 29781;
  }
  let obsClient = new ObsClient({
    // access_key_id: obsId.value,
    // secret_access_key: obsKey.value,
    access_key_id: 'TODD7COQ9OY55YNUYHEC',
    secret_access_key: 'DmX1sTbrl0OGRnPKDTlXvup6DP2S9Txe4hKy6eRO',
    server: 'https://obs.cn-east-3.myhuaweicloud.com'
  });
  obsClient.deleteObject(
    {
      Bucket: bucket.value,
      Key: dataKey
    },
    function (err, result) {
      if (err) {
        console.log('Error-->' + err);
      } else {
        console.log('Status-->' + result.CommonMsg.Status);
      }
    }
  );
}
const textData = ref('');
const wangEditorData = ref(''); // 富文本内容
const html = ref(''); // 富文本html
// 富文本内容带标签
function catchData(e) {
  if (e === '<p><br/></p>') {
    html.value = '';
  } else {
    html.value = e;
    change('TextRichField');
  }
}
// 富文本内容
function catchPureData(e) {
  textData.value = e;
}
</script>
<style lang="less" scoped>
@import './index.less';
</style>
